<?php
/**
 * MatchDart! is a darts event ranking table component for joomla
 * 
 * @version		2.0.1 | $Id: event.php 116 2009-10-12 14:08:54Z mwi.nor $
 * @package		MatchDart!
 * @subpackage	Admin
 * @copyright	Copyright (C) 2005 - 2009 Marco Wilde. All rights reserved.
 * @license		GNU/GPL, see LICENSE.php
 * @author		Marco Wilde, <mailto://info@matchdart.de>
 * @link		http://www.matchdart.de
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.application.component.model' );

class MatchdartModelEvent extends JModel
{
    protected $_data = null;
    protected $_id = null;
    protected $_defaultid = null;
    protected $_playerlist;
    protected $_teamlist;
    

    public function __construct()
    {
        parent::__construct();

        $array = JRequest::getVar('cid',  0, '', 'array');
        $this->setId((int)$array[0]);
    }

    public function setId($id)
    {
        // Set id and wipe data
        $this->_id        = $id;
        $this->_data    = null;
    }

    public function getData()
    {

    	// Load the data
        if(empty( $this->_data )) {
            $query = 'SELECT * FROM #__md_events '.
                 ' WHERE EventID = '.(int) $this->_id;
            $this->_db->setQuery( $query );
            $this->_data = $this->_db->loadObject();
        }
        if (!$this->_data) {
            $this->_data = $this->getTable('events');
            $this->_data->id = 0;
        }
        return $this->_data;
    }
    

    public function store()
    {
        $row =& $this->getTable('events');
        $data = JRequest::get( 'post' );
        
        //get checkbox values
        $data['EventUseDraws'] = JRequest::getVar( 'EventUseDraws', 0, 'post', 'int' );
        $data['EventUsePlayoffs'] = JRequest::getVar( 'EventUsePlayoffs', 0, 'post', 'int' );
        $data['EventUseSets'] = JRequest::getVar( 'EventUseSets', 0, 'post', 'int' );
        $data['EventUseTeams'] = JRequest::getVar( 'EventUseTeams', 0, 'post', 'int' );
        $data['EventUseVenues'] = JRequest::getVar( 'EventUseVenues', 0, 'post', 'int' );
        $data['EventUseXStats'] = JRequest::getVar( 'EventUseXStats', 0, 'post', 'int' );
        
        $data['EventRemarks'] = JRequest::getVar( 'EventRemarks', null, 'post', 'string', JREQUEST_ALLOWRAW );
        $data['EventTableLegend'] = JRequest::getVar( 'EventTableLegend', null, 'post', 'string', JREQUEST_ALLOWRAW );
        
        $data['playerlist'] = JRequest::getVar( 'playerlist', -1, 'post', 'array' );
        $data['teamlist'] = JRequest::getVar( 'teamlist', -1, 'post', 'array' );
        
        //get players / teams
        $data['EventPlayers'] = implode(",",$data['playerlist']);
        $data['EventTeams'] = implode(",",$data['teamlist']);
        
        // Bind the form fields to the hello table
        if (!$row->bind($data)) {
            $this->setError($this->_db->getErrorMsg());
            return false;
        }

        // Make sure the hello record is valid
        if (!$row->check()) {
            $this->setError($this->_db->getErrorMsg());
            return false;
        }

        // Store the entry to the database
        if (!$row->store()) {
            $this->setError($this->_db->getErrorMsg());
            return false;

        }
        return true;
    }

    public function delete()
    {
        $cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );
        $row =& $this->getTable('events');

        foreach($cids as $cid) {

        	// delete only events w/o matches
        	$query = 'SELECT * FROM #__md_matches WHERE MatchEventID='.$cid;
        	$number = $this->_getListCount($query);
        	
        	if ($number != 0){
        		return false;
        	} else { 
	            if (!$row->delete( $cid )) {
	                $this->setError( $row->_db->getErrorMsg() );
	                return false;
	            }
        	}
        }

        return true;
    }

    /**
     * publish event
     */
    public function publish()
    {
        $cids = implode(',',JRequest::getVar( 'cid', array(0), 'post', 'array' ));
        //$row =& $this->getTable('events');
		
			$query = 'UPDATE #__md_events '.' SET EventPublish = 1 WHERE EventID in ('.$cids.')';
			$this->_db->setQuery( $query );
			$result = $this->_db->loadResult();
        
        if ($result){
        $message->msg = 'MD_OPERATION_SELECTPUBLISHED';
        $message->type = 'message';
        }

        return $message;
    }

    /**
     * unpublish event
     */
    public function unpublish()
    {
        $cids = implode(',',JRequest::getVar( 'cid', array(0), 'post', 'array' ));
        //$row =& $this->getTable('events');
		
			$query = 'UPDATE #__md_events '.' SET EventPublish = 0 WHERE EventDefault = 0 AND EventID in ('.$cids.')';
			$this->_db->setQuery( $query );
			$result = $this->_db->loadResult();
        
        if ($result){
        $message->msg = 'MD_OPERATION_SELECTUNPUBLISHED';
        $message->type = 'message';
        }

        return $message;
    }
    
    
    /**
     * toggle publish / unpublish event
     */
    public function togglePublish()
    {
        $cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );
        //$row =& $this->getTable('events');
		
        foreach($cids as $cid) {
        	
        	$eventdata =& $this->getData();

            if ($eventdata->EventPublish == 1) {
				$query = 'UPDATE #__md_events '.' SET EventPublish = 0 WHERE EventID = '.(int) $cid;
		        $message->msg = 'MD_OPERATION_UNPUBLISHED';
        		$message->type = 'message';
            } else {
				$query = 'UPDATE #__md_events '.' SET EventPublish = 1 WHERE EventID = '.(int) $cid;
		        $message->msg = 'MD_OPERATION_PUBLISHED';
        		$message->type = 'message';
            }
			echo 'query '.$query.'<br>';
			$this->_db->setQuery( $query );
			$result = $this->_db->loadResult();
        }
		
        if ($result) {
        	return $message;
        }
    }
    
    
    /**
     * set default event
     */
    public function setDefault()
    {
		$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );
		
		//only 1 default event possible
		if (count($cids) != 1) {
			$this->setError('MD_ERRONEDEFAULT');
			return false;
		} else {
			$eventdata =& $this->getData();
			
			$query = 'UPDATE #__md_events '.' SET EventDefault = 0';
			$this->_db->setQuery( $query );
			$this->_db->loadResult();

			$query = 'UPDATE #__md_events '.' SET EventDefault = 1, EventPublish = 1 WHERE EventID = '.$this->_id;
			$this->_db->setQuery( $query );
			$this->_db->loadResult();
		}
    }
    
    public function getPlayerlist()
    {
//    	$app = &JFactory::getApplication();

//		$context			= 'com_matchdart.event';
//		$playerlist		= $app->getUserStateFromRequest( $context.'$playerselect',		'playerselect',		'0',	'cmd' );
    	$eventdata = $this->getData();
        $eventplayers = explode(",",$eventdata->EventPlayers);
    	
    	if (empty($this->_playerlist))
    	{
    	//$currentValue = $showevent;
        $query = 'SELECT * FROM #__md_players ORDER BY PlayerName';
        $players = $this->_getList($query);

        $k=1;
        //FIXME: 'foreach' --> error if events table empty
        $option[0] = JHTML::_('select.option', '-1', JText::_( 'MD_SELECT_NONE'));
        foreach ($players as $player){
        	$option[$k] = JHTML::_('select.option', $player->PlayerID, $player->PlayerName);
        	$k++;
        }
        
        $this->_playerlist = JHTML::_('select.genericlist', $option, 'playerlist[]', 'class="inputbox" size="5" multiple="multiple"', 'value', 'text', $eventplayers,'playerlist');
        
    	}
    	return $this->_playerlist;
    }
    
    public function getTeamlist()
    {
//    	$app = &JFactory::getApplication();

//		$context			= 'com_matchdart.event';
//		$playerlist		= $app->getUserStateFromRequest( $context.'$playerselect',		'playerselect',		'0',	'cmd' );
    	$eventdata = $this->getData();
        $eventteams = explode(",",$eventdata->EventTeams);
    	
    	if (empty($this->_teamlist))
    	{
    	//$currentValue = $showevent;
        $query = 'SELECT * FROM #__md_teams ORDER BY TeamName';
        $teams = $this->_getList($query);

        $k=1;
        //FIXME: 'foreach' --> error if events table empty
        $option[0] = JHTML::_('select.option', '-1', JText::_( 'MD_SELECT_NONE'));
        foreach ($teams as $team){
        	$option[$k] = JHTML::_('select.option', $team->TeamID, $team->TeamName);
        	$k++;
        }
        
        $this->_teamlist = JHTML::_('select.genericlist', $option, 'teamlist[]', 'class="inputbox" size="5" multiple="multiple"', 'value', 'text', $eventteams,'teamlist');
        
    	}
    	return $this->_teamlist;
    }

}
?>